'use client'

import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { cn } from '~/core/utils'
import { 
  Loader2, 
  Plus, 
  Search, 
  EllipsisVertical, 
  Trash2,
  ChevronLeft,
  ChevronRight,
  Pin,
  PinOff,
  Check,
  CheckSquare,
  Square
} from 'lucide-react'
import { Button } from '~/components/ui/button'
import { 
  Tooltip, 
  TooltipContent, 
  TooltipTrigger 
} from '~/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from '~/components/ui/dropdown-menu'
import { useStore } from "~/core/store"
import { useEffect, useState } from 'react'

export type HistoryItem = {
  id: string
  title: string
  timestamp: string
}

type SidebarProps = {
  className?: string
  isExpanded: boolean
  onToggle: () => void
  onNewChat: () => void;
  onOpenSearch: () => void;
}

export function Sidebar({ 
  className, 
  onNewChat,
  isExpanded,
  onToggle,
  onOpenSearch
}: SidebarProps) {
  const { 
    auth, 
    sessionList, 
    loadingSessions, 
    fetchSessionList,
    pinSession,
    unpinSession,
    pinnedSessions,
    deleteSession
  } = useStore();
  
  // 多选状态管理
  const [selectedSessions, setSelectedSessions] = useState<string[]>([]);
  const [deleteConfirmation, setDeleteConfirmation] = useState<{
    show: boolean,
    sessionId: string | null
  }>({
    show: false,
    sessionId: null
  });
  const [showBatchDeleteConfirmation, setShowBatchDeleteConfirmation] = useState(false);
  const [isMultiSelectMode, setIsMultiSelectMode] = useState(false);
  const [hoveredSession, setHoveredSession] = useState<string | null>(null);
  const [menuOpenState, setMenuOpenState] = useState<Record<string, boolean>>({});
  
  const primaryColor = "#0077b6";

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return format(date, 'yyyy-MM-dd HH:mm', { locale: zhCN });
    } catch (e) {
      return dateString;
    }
  };
  
  // 处理会话操作
  const handleSessionAction = (
    action: 'delete' | 'togglePin' | 'multiSelect',
    sessionId: string | null = null
  ) => {
    if (action === 'togglePin' && sessionId) {
      if (pinnedSessions.includes(sessionId)) {
        unpinSession(sessionId);
      } else {
        pinSession(sessionId);
      }
    } else if (action === 'delete' && sessionId) {
      setDeleteConfirmation({
        show: true,
        sessionId
      });
    } else if (action === 'multiSelect') {
      setIsMultiSelectMode(true);
    }
    
    // 关闭菜单
    if (sessionId) {
      setMenuOpenState(prev => ({...prev, [sessionId]: false}));
    }
  };
  
  // 确认删除会话
  const confirmDeleteSession = () => {
    if (deleteConfirmation.sessionId) {
      useStore.getState().deleteSession(deleteConfirmation.sessionId);
    }
    setDeleteConfirmation({
      show: false,
      sessionId: null
    });
  };
  
  // 取消删除
  const cancelDelete = ()=> {
    setDeleteConfirmation({
      show: false,
      sessionId: null
    });
  };
  
  // 确认批量删除会话
  const confirmBatchDelete = () => {
    selectedSessions.forEach(sessionId => {
      useStore.getState().deleteSession(sessionId);
    });
    setSelectedSessions([]);
    setShowBatchDeleteConfirmation(false);
    setIsMultiSelectMode(false);
  };

  // 取消批量删除
  const cancelBatchDelete = () => {
    setShowBatchDeleteConfirmation(false);
  };
  
  // 处理会话选择
  const handleSessionSelect = (sessionId: string) => {
    if (selectedSessions.includes(sessionId)) {
      setSelectedSessions(selectedSessions.filter(id => id !== sessionId));
    } else {
      setSelectedSessions([...selectedSessions, sessionId]);
    }
  };
  
  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedSessions.length === sessionList.length) {
      setSelectedSessions([]);
    } else {
      setSelectedSessions(sessionList.map(session => session.session_id));
    }
  };

  // 切换菜单状态
  const toggleMenu = (sessionId: string, open: boolean) => {
    setMenuOpenState(prev => ({
      ...prev,
      [sessionId]: open
    }));
  };

  useEffect(() => {
    if (auth.isLoggedIn) {
      fetchSessionList();
    } else {
      useStore.setState({ sessionList: [] });
    }
  }, [auth.isLoggedIn, fetchSessionList]);
  
  // 渲染历史记录区域
  const renderHistorySection = () => {
    if (!auth.isLoggedIn) {
      return (
        <div className="text-sm text-muted-foreground text-center p-4">
          登录后查看历史记录
        </div>
      );
    }
    
    if (loadingSessions) {
      return (
        <div className="flex justify-center py-4">
          <Loader2 className="h-5 w-5 animate-spin text-primary" />
        </div>
      );
    }
    
    if (sessionList.length === 0) {
      return (
        <div className="text-sm text-muted-foreground text-center p-4">
          暂无历史记录
        </div>
      );
    }
    
    // 分组渲染置顶和非置顶会话
    const renderSessionGroup = (sessions: typeof sessionList, isPinned: boolean) => {
      if (sessions.length === 0) return null;
      
      return (
        <div className="mb-4">
          {isPinned && (
            <h4 className="text-xs font-medium text-gray-500 mb-2 pl-2">置顶会话</h4>
          )}
          <div className="space-y-1">
            {sessions.map((item) => {
              const isPinnedItem = pinnedSessions.includes(item.session_id);
              const isSelected = selectedSessions.includes(item.session_id);
              
              return (
                <div
                  key={item.session_id}
                  className={cn(
                    "group p-3 rounded-md transition-colors cursor-pointer border relative",
                    isSelected ? "bg-blue-50 border-blue-200" : "border-gray-100 hover:bg-gray-50"
                  )}
                  onMouseEnter={() => setHoveredSession(item.session_id)}
                  onMouseLeave={() => setHoveredSession(null)}
                  onClick={() => {
                    if (isMultiSelectMode) {
                      handleSessionSelect(item.session_id);
                    } else {
                      useStore.getState().loadSessionHistory(item.session_id);
                    }
                  }}
                >
                  <div className="flex items-start">
                    {isMultiSelectMode && (
                      <div 
                        className="flex items-center justify-center w-5 h-5 rounded border border-gray-300 mr-3"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleSessionSelect(item.session_id);
                        }}
                      >
                        {isSelected && (
                          <Check className="w-4 h-4 text-blue-600" />
                        )}
                      </div>
                    )}
                    
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center">
                        {isPinned && (
                          <Pin className="w-3 h-3 text-blue-500 mr-1" />
                        )}
                        <div className="text-sm truncate text-gray-800">
                          {item.preview || "未命名会话"}
                        </div>
                      </div>
                      <div className="text-xs text-gray-500">
                        {formatDate(item.updated_at)}
                      </div>
                    </div>
                    
                    {/* 三点按钮菜单 */}
                    {!isMultiSelectMode && (
                      <div 
                        className={cn(
                          "ml-2 flex items-center justify-center w-6 h-6 rounded hover:bg-gray-100 transition-colors",
                          hoveredSession === item.session_id ? "opacity-100" : "opacity-0"
                        )}
                        onClick={(e) => e.stopPropagation()}
                      >
                        <DropdownMenu
                          open={menuOpenState[item.session_id] || false}
                          onOpenChange={(open) => toggleMenu(item.session_id, open)}
                        >
                          <DropdownMenuTrigger asChild>
                            <button
                              className="text-gray-400 hover:text-gray-600 focus:outline-none rounded-full w-6 h-6 flex items-center justify-center"
                              onClick={(e) => {
                                e.stopPropagation();
                                toggleMenu(item.session_id, !menuOpenState[item.session_id]);
                              }}
                            >
                              <EllipsisVertical size={16} />
                            </button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent 
                            align="end" 
                            className="w-48 z-50 shadow-lg rounded-lg border border-gray-200"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <DropdownMenuItem 
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSessionAction('multiSelect', item.session_id);
                              }}
                              className="cursor-pointer px-4 py-2 hover:bg-gray-100"
                            >
                              <CheckSquare className="mr-2 h-4 w-4 text-gray-600" />
                              <span>多选</span>
                            </DropdownMenuItem>
                            <DropdownMenuItem 
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSessionAction('togglePin', item.session_id);
                              }}
                              className="cursor-pointer px-4 py-2 hover:bg-gray-100"
                            >
                              {isPinnedItem ? (
                                <>
                                  <PinOff className="mr-2 h-4 w-4 text-gray-600" />
                                  <span>取消置顶</span>
                                </>
                              ) : (
                                <>
                                  <Pin className="mr-2 h-4 w-4 text-gray-600" />
                                  <span>置顶</span>
                                </>
                              )}
                            </DropdownMenuItem>
                            <DropdownMenuSeparator className="border-t border-gray-200" />
                            <DropdownMenuItem 
                              className="text-red-600 focus:text-red-600 px-4 py-2 hover:bg-red-50 cursor-pointer"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSessionAction('delete', item.session_id);
                              }}
                            >
                              <Trash2 className="mr-2 h-4 w-4" />
                              <span>删除</span>
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      );
    };
    
    return (
      <>
        {renderSessionGroup(
          sessionList.filter(item => pinnedSessions.includes(item.session_id)), 
          true
        )}
        <h4 className="text-xs font-medium text-gray-500 mb-2 pl-2">历史对话</h4>
        {renderSessionGroup(
          sessionList.filter(item => !pinnedSessions.includes(item.session_id)), 
          false
        )}
      </>
    );
  };
  
  // 在收起状态下只显示这两个按钮
  if (!isExpanded) {
    return (
      <div className={cn(
        "h-full flex flex-col justify-start items-center py-4 space-y-4 bg-white border-r",
        className
      )}>
        {/* 折叠/展开按钮 */}
        <Tooltip>
          <TooltipTrigger asChild>
            <button
              className={cn(
                "flex items-center justify-center w-8 h-8 rounded border",
                "hover:opacity-90 transition-opacity",
                "bg-[#0077b6] border-[#0000]"
              )}
              onClick={onToggle}
            >
              <ChevronRight className="w-5 h-5 text-white" />
            </button>
          </TooltipTrigger>
          <TooltipContent side="right" className="bg-white text-black text-xs shadow-md">
            展开侧边栏
          </TooltipContent>
        </Tooltip>
        
        {/* 新建对话按钮 */}
        <Tooltip>
          <TooltipTrigger asChild>
            <button
              className={cn(
                "flex items-center justify-center rounded-full w-9 h-9",
                "bg-[#0077b6] hover:bg-[#005a8c] text-white", 
                "transform hover:scale-105 transition-transform duration-200",
                "shadow-md hover:shadow-lg focus:outline-none" 
              )}
              onClick={onNewChat}
            >
              <Plus className="w-5 h-5 text-white" />
            </button>
          </TooltipTrigger>
          <TooltipContent side="right" className="bg-white text-black text-xs shadow-md">
            新建对话
          </TooltipContent>
        </Tooltip>
      </div>
    );
  }
  
  // 展开状态下的完整侧边栏
  return (
    <div 
      className={cn(
        "h-full flex flex-col bg-white border-r",
        isExpanded ? "px-4 py-4 w-64" : "px-3 py-4 w-[56px]",
        className
      )}
    >
      {/* 顶部功能区 */}
      <div className="space-y-3">
        {/* 控制按钮区域 */}
        <div className="flex justify-between items-center">
          {/* 收起按钮 */}
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                className={cn(
                  "flex items-center justify-center w-8 h-8 rounded border",
                  "hover:opacity-90 transition-opacity",
                  "bg-[#0077b6] border-[#0000]"
                )}
                onClick={onToggle}
              >
                <ChevronLeft className="w-5 h-5 text-white" />
              </button>
            </TooltipTrigger>
            <TooltipContent side="right" className="bg-white text-black text-xs shadow-md">
              收起侧边栏
            </TooltipContent>
          </Tooltip>
          
          {/* 搜索按钮 */}
          <Button 
            variant="ghost"
            className="h-8 text-gray-600 hover:bg-blue-50 hover:text-blue-600"
            onClick={onOpenSearch}
          >
            <Search size={16} className="mr-2" />
            <span className="text-sm">搜索</span>
          </Button>
        </div>
        
        {/* 新建对话按钮 */}
        <div className="flex justify-center">
          <Button 
            className={cn(
              "flex items-center justify-center rounded-full h-10",
              "w-full px-4",
              "bg-[#0077b6] hover:bg-[#005a8c] text-white transition-all",
              "shadow-md hover:shadow-lg"
            )}
            onClick={onNewChat}
          >
            <Plus className="w-4 h-4 mr-2" />
            <span className="font-medium">
              新建对话
            </span>
          </Button>
        </div>
        
        {/* 多选操作栏 */}
        {isMultiSelectMode && (
          <div className="bg-blue-50 rounded-lg p-3 border border-blue-100">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-3">
                <div 
                  className="w-5 h-5 flex items-center justify-center rounded border border-gray-300 cursor-pointer bg-white"
                  onClick={toggleSelectAll}
                >
                  {selectedSessions.length === sessionList.length ? (
                    <Check className="w-4 h-4 text-blue-600" />
                  ) : (
                    <Square className="w-4 h-4 text-gray-400" />
                  )}
                </div>
                <span className="text-sm text-gray-700">
                  {selectedSessions.length} 个已选
                </span>
              </div>
              <div className="flex space-x-2">
                <Button 
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setIsMultiSelectMode(false);
                    setSelectedSessions([]);
                  }}
                  className="border-gray-300 text-gray-700 hover:bg-gray-100"
                >
                  取消
                </Button>
                <Button 
                  variant="destructive"
                  size="sm"
                  onClick={() => setShowBatchDeleteConfirmation(true)}
                  className="flex items-center bg-red-600 hover:bg-red-700"
                >
                  <Trash2 className="h-4 w-4 mr-1" />
                  <span>删除</span>
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>
      
      {/* 历史记录区域 - 可滚动 */}
      <div className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent mt-4">
        {renderHistorySection()}
      </div>
      
      {/* 单个删除确认对话框 */}
      {deleteConfirmation.show && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[1000] backdrop-blur-sm">
          <div className="bg-white rounded-lg p-6 w-96 shadow-xl">
            <h3 className="text-lg font-semibold mb-4">确认删除</h3>
            <p className="text-gray-600 mb-6">
              确定要删除此对话吗？删除后无法恢复。
            </p>
            <div className="flex justify-end space-x-3">
              <Button 
                variant="outline"
                onClick={cancelDelete}
                className="border-gray-300 text-gray-700 hover:bg-gray-50 px-4 py-2"
              >
                取消
              </Button>
              <Button 
                variant="destructive"
                onClick={confirmDeleteSession}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2"
              >
                删除
              </Button>
            </div>
          </div>
        </div>
      )}
      
      {/* 批量删除确认对话框 */}
      {showBatchDeleteConfirmation && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[1000] backdrop-blur-sm">
          <div className="bg-white rounded-lg p-6 w-96 shadow-xl">
            <h3 className="text-lg font-semibold mb-4">批量删除确认</h3>
            <p className="text-gray-600 mb-6">
              确定要删除选中的 {selectedSessions.length} 个对话吗？此操作无法恢复。
            </p>
            <div className="flex justify-end space-x-3">
              <Button 
                variant="outline"
                onClick={cancelBatchDelete}
                className="border-gray-300 text-gray-700 hover:bg-gray-50 px-4 py-2"
              >
                取消
              </Button>
              <Button 
                variant="destructive"
                onClick={confirmBatchDelete}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2"
              >
                删除({selectedSessions.length})
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}